package com.example.owner.aop;

import io.micronaut.aop.InterceptorBean;
import io.micronaut.aop.MethodInterceptor;
import io.micronaut.aop.MethodInvocationContext;
import io.micronaut.core.type.MutableArgumentValue;
import jakarta.inject.Singleton;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Singleton
@InterceptorBean(NullCheck.class)
public class NullCheckInterceptor implements MethodInterceptor<Object, Object> {
    @Override
    public Object intercept(MethodInvocationContext<Object, Object> context) {
        log.info("intercept AroundInterceptor {}", context);
        Optional<Map.Entry<String, MutableArgumentValue<?>>> nullParam = context.getParameters()
                .entrySet()
                .stream()
                .filter(entry -> {
                    MutableArgumentValue<?> argumentValue = entry.getValue();
                    return Objects.isNull(argumentValue.getValue());
                })
                .findFirst(); // (3)
        if (nullParam.isPresent()) {
            throw new IllegalArgumentException("Null parameter [" + nullParam.get().getKey() + "] not allowed"); // (4)
        }
        return context.proceed(); // (5)
    }
}
